package com.lb.jwitter.service;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.jws.WebService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lb.jwitter.*;
import com.lb.jwitter.hibernate.*;
import com.lb.jwitter.util.ChumanoLogger;
import com.lb.jwitter.util.ConditionReport;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;


@Service("tbl_DKMH_KetquaService")
@Transactional
@WebService(endpointInterface = "com.lb.jwitter.service.Tbl_DKMH_KetquaService")
public class Tbl_DKMH_KetquaServiceImpl implements Tbl_DKMH_KetquaService,Serializable {

   private Log log = LogFactory.getLog(Tbl_DKMH_KetquaServiceImpl.class);
   private static final long serialVersionUID = -8740095022264495229L;
   
   @Autowired
	@Qualifier("tbl_CTDT_MonHocDAO")
	private Tbl_CTDT_MonHocDAO _tbl_CTDT_MonHocDao;
   
   @Autowired
   @Qualifier("tbl_DKMH_KetquaDAO")
   private Tbl_DKMH_KetquaDAO _tbl_DKMH_KetquaDao;

   @Autowired
   @Qualifier("tbl_DKMH_DotDKDAO")
   private Tbl_DKMH_DotDKDAO _tbl_DKMH_DotDKDao;

   @Autowired
   @Qualifier("tbl_ThongTin_HocVienDAO")
   private Tbl_ThongTin_HocVienDAO _tbl_ThongTin_HocVienDao;

   @Autowired
   @Qualifier("tbl_ThongTin_NhomLop_MonHocDAO")
   private Tbl_ThongTin_NhomLop_MonHocDAO _tbl_ThongTin_NhomLop_MonHocDao;

   @Autowired
   @Qualifier("tbl_CanBoDAO")
   private Tbl_CanBoDAO _tbl_CanBoDao;

   public final List<Tbl_DKMH_Ketqua> findAlltbl_DKMH_Ketqua(int pageSize, int page){
   List<Tbl_DKMH_Ketqua> result = get_tbl_DKMH_KetquaDao().findAll(pageSize, page);
       log.info("Number of user in DB:: "+result.size());
       return result;
   }

   @Transactional(noRollbackFor=IllegalArgumentException.class)
   public final Long createtbl_DKMH_Ketqua(Tbl_DKMH_Ketqua obj){
       return _tbl_DKMH_KetquaDao.save(obj);
   }

   public final void updatetbl_DKMH_Ketqua(Tbl_DKMH_Ketqua obj){
       _tbl_DKMH_KetquaDao.update(obj);
   }//end update methode

   public final Tbl_DKMH_Ketqua gettbl_DKMH_Ketqua (Long id){
       log.info("Try to retrieve the tbl_DKMH_Ketqua: "+id);
       return get_tbl_DKMH_KetquaDao().get(id);
   }

   public void deletetbl_DKMH_Ketqua(Long id){
       log.info("Try to delete the tbl_DKMH_Ketqua by Id : "+ id);
       if(_tbl_DKMH_KetquaDao.exists(id)){
	    _tbl_DKMH_KetquaDao.delete(id);
       } else {
       	throw new IllegalArgumentException("EmployeeId '"+id+"' does not exists");
       }
   }

   public void deleteListtbl_DKMH_Ketqua(String[] listId){
       for(String id : listId){
   	    deletetbl_DKMH_Ketqua(Long.parseLong(id));
       }
   }

   public List<Tbl_DKMH_Ketqua> findtbl_DKMH_KetquaByCondition(List<ConditionReport> cons,int pageSize,int page){ 
       return _tbl_DKMH_KetquaDao.findByCondition(Tbl_DKMH_Ketqua.class, cons, pageSize, page); 
   } 
 
   public int counttbl_DKMH_KetquaByCondition(List<ConditionReport> cons){ 
       return _tbl_DKMH_KetquaDao.countByCondition(Tbl_DKMH_Ketqua.class, cons); 
   } 
 
   public final Tbl_DKMH_KetquaDAO get_tbl_DKMH_KetquaDao() {
   	return _tbl_DKMH_KetquaDao;
   }
   public final void set_tbl_DKMH_KetquaDao(Tbl_DKMH_KetquaDAO obj) {
   	this._tbl_DKMH_KetquaDao = obj;
   }

   public Tbl_DKMH_DotDKDAO get_tbl_DKMH_DotDKDao() {
       return _tbl_DKMH_DotDKDao;
   }
   public void set_tbl_DKMH_DotDKDao(Tbl_DKMH_DotDKDAO _tbl_DKMH_DotDKDao) {
       this._tbl_DKMH_DotDKDao = _tbl_DKMH_DotDKDao;
   }

   public Tbl_ThongTin_HocVienDAO get_tbl_ThongTin_HocVienDao() {
       return _tbl_ThongTin_HocVienDao;
   }
   public void set_tbl_ThongTin_HocVienDao(Tbl_ThongTin_HocVienDAO _tbl_ThongTin_HocVienDao) {
       this._tbl_ThongTin_HocVienDao = _tbl_ThongTin_HocVienDao;
   }

   public Tbl_ThongTin_NhomLop_MonHocDAO get_tbl_ThongTin_NhomLop_MonHocDao() {
       return _tbl_ThongTin_NhomLop_MonHocDao;
   }
   public void set_tbl_ThongTin_NhomLop_MonHocDao(Tbl_ThongTin_NhomLop_MonHocDAO _tbl_ThongTin_NhomLop_MonHocDao) {
       this._tbl_ThongTin_NhomLop_MonHocDao = _tbl_ThongTin_NhomLop_MonHocDao;
   }

   public Tbl_CanBoDAO get_tbl_CanBoDao() {
       return _tbl_CanBoDao;
   }
   public void set_tbl_CanBoDao(Tbl_CanBoDAO _tbl_CanBoDao) {
       this._tbl_CanBoDao = _tbl_CanBoDao;
   }
   
   public void createListtbl_DKMH_KetQuaByJSON(int dotDKId, String data, Tbl_TaiKhoan taiKhoan){
	   try {
			ChumanoLogger.init(Tbl_DKMH_KetquaServiceImpl.class.getName());
			ChumanoLogger.log("0BAT DAU INSERT DU LIEU");
			List<Tbl_DKMH_Ketqua> tbl_DKMH_Ketquas = new ArrayList<Tbl_DKMH_Ketqua>();

			Tbl_DKMH_DotDK dotdk = new Tbl_DKMH_DotDK();
			dotdk.setId(new Long(dotDKId));
			
			
			JSONArray jsons = (JSONArray) JSONSerializer.toJSON(data);
			for (int i = 0; i < jsons.size(); i++) {
				JSONObject obj = jsons.getJSONObject(i);
				String logStr ="";
				//-------------------------------------
				//Lay du lieu
				//MSSV	MaMonHoc	MaNhom	MaBaiTap	NhomBaiTap	KQ	GhiChu	Huy	DieuChinh	XuLy Khoa
				String mssv = obj.getString("MSSV").trim();
				String maMH = obj.getString("MAMONHOC").trim();
				String maNhom = obj.getString("MANHOM").trim();
				String maMHBT = obj.getString("MABAITAP").trim();
				String maNhomBT = obj.getString("NHOMBAITAP").trim();
				
				String ketqua = obj.getString("KQ").trim();
				String ghichu = obj.getString("GHICHU");
				//String huy = obj.getString("HUY");
				String dieuchinh = obj.getString("DIEUCHINH");
				String xuly = obj.getString("XULY");
				
				Boolean khoaMonHocYN = false;
				String str = obj.getString("KHOA");
				if(str!=null && !str.isEmpty()){
					khoaMonHocYN = true;
				}
				
				String khoa = khoaMonHocYN?"Y":"N";
				
				logStr ="[ " + (i+1)+ " - " 
				+ "MSSV: " + mssv + " - " 
				+ "MAMH: " + maMH + " - " 
				+ "MANHOM: " + maNhom + " - " 
				+ "MAMHBT: " + maMHBT + " - " 
				+ "MANHOMBT: " + maNhomBT + " - " 
				
				+ "KETQUA: " + ketqua + " - "
				+ "DIEUCHINH: " + dieuchinh + " - " 
				+ "XULY: " + xuly + " - " 
				+ "]";
				//=====================================
				// kiem tra DU LIEU TON TAI				
				//HOC VIEN
				List<Long> hocvienids = findHocVienId(mssv);
				if(hocvienids==null || hocvienids.size()==0)
				{
					ChumanoLogger.log(logStr + " <NOT MSSV>");
					continue;
				}
				Tbl_ThongTin_HocVien hocvien = new Tbl_ThongTin_HocVien();
				hocvien.setId(hocvienids.get(0));
				
				Tbl_ThongTin_NhomLop_MonHoc nlmh =null;
				Tbl_ThongTin_NhomLop_MonHoc nlmhbt =null;
				
				//MON HOC
				List<Long> monhocids = findMonHocId(maMH);
				if(monhocids==null || monhocids.size()==0)
				{
					ChumanoLogger.log(logStr + " <NOT MAMH>");
					continue;
				}
				
				if(ketqua.equals("*")){		
					//NHOM LOP MON HOC
					List<Long> nlmhids = findNhomLopMonHocId(maNhom,monhocids.get(0));
					if(nlmhids==null || nlmhids.size()==0)
					{
						ChumanoLogger.log(logStr + " <NOT NLMH>");
						continue;
					}
					nlmh= new Tbl_ThongTin_NhomLop_MonHoc();
					nlmh.setId(nlmhids.get(0));
					
					//MON BAI TAP
					//NHOM LOP BAI TAP
					nlmhbt =null;
					if(maMHBT!=null&&!maMHBT.equals("")
							&&maNhomBT!=null&&!maNhomBT.equals("")){
						//MON HOC
						List<Long> monhocbtids = findMonHocId(maMHBT);
						if(monhocbtids==null || monhocbtids.size()==0)
						{
							ChumanoLogger.log(logStr + " <NOT MAMHBT>");
							continue;
						}
									
						//NHOM LOP MON HOC
						List<Long> nlmhbtids = findNhomLopMonHocId(maNhomBT,monhocbtids.get(0));
						if(nlmhbtids==null || nlmhbtids.size()==0)
						{
							ChumanoLogger.log(logStr + " <NOT NLMHBT>");
							continue;
						}
						nlmhbt = new Tbl_ThongTin_NhomLop_MonHoc();
						nlmhbt.setId(nlmhbtids.get(0));
						
						//--------------------------------------------------
						Tbl_DKMH_Ketqua ketquadkbt = new Tbl_DKMH_Ketqua();
						//tim ket qua da dang ky de cap nhat
						List<Tbl_DKMH_Ketqua> kqsbt = findKetQuaDKId(dotdk.getId(), hocvien.getId(),monhocbtids.get(0));
						if(kqsbt!=null&&kqsbt.size()>0){
							ketquadkbt = kqsbt.get(0);
							logStr+= "< EXIST KQBT>";
						}
						
						ketquadkbt.setHocVienId(hocvien);
						ketquadkbt.setNLMHId(nlmhbt);
						ketquadkbt.setKetQua(ketqua);
						ketquadkbt.setKetQuaLyDo(ghichu);
						ketquadkbt.setMaDieuChinh(dieuchinh);
						ketquadkbt.setTinhTrang(xuly);
						ketquadkbt.setXacNhanYN(true);	//ep cho xac nhan luon

						ketquadkbt.setDotDKId(dotdk);
						ketquadkbt.setCanBoID(taiKhoan.getCanBoId());
						ketquadkbt.setNgayCapNhatCanBo(new Date());
						
						ketquadkbt.setKhoaMonHocYN(khoa);
						//--------------------------------
						tbl_DKMH_Ketquas.add(ketquadkbt);
					}
					
					//====================================
					Tbl_DKMH_Ketqua ketquadk = new Tbl_DKMH_Ketqua();
					//tim ket qua da dang ky de cap nhat
					List<Tbl_DKMH_Ketqua> kqs = findKetQuaDKId(dotdk.getId(), hocvien.getId(), monhocids.get(0));
					if(kqs!=null&&kqs.size()>0){
						ketquadk = kqs.get(0);
						logStr+= "< EXIST KQ>";
					}
					
					ketquadk.setHocVienId(hocvien);
					ketquadk.setNLMHId(nlmh);
					if(nlmhbt!=null)ketquadk.setNLMHBTId(nlmhbt);
					
					ketquadk.setKetQua(ketqua);
					ketquadk.setKetQuaLyDo(ghichu);
					ketquadk.setMaDieuChinh(dieuchinh);
					ketquadk.setTinhTrang(xuly);
					ketquadk.setXacNhanYN(true);	//ep cho xac nhan luon

					ketquadk.setDotDKId(dotdk);
					ketquadk.setCanBoID(taiKhoan.getCanBoId());
					ketquadk.setNgayCapNhatCanBo(new Date());

					ketquadk.setKhoaMonHocYN(khoa);
					//--------------------------------
					tbl_DKMH_Ketquas.add(ketquadk);
				}else{
					//NEU KETQUA khac *
					
				}

				ChumanoLogger.log(logStr);
			}// end for

			_tbl_DKMH_KetquaDao.saveOrUpdateAll(tbl_DKMH_Ketquas);
		} catch (Exception e) {
			ChumanoLogger.log("ERROR: " +e.getMessage());
			   System.out.println("------------ERROR CHUMANO-------------");
			   e.printStackTrace();
			   System.out.println("=================================");
		}
		   
		ChumanoLogger.stop();
   }
   
   private List<Long> findHocVienId(String ma){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("MSSV");
	        con.setValue1(ma);
	        con.setOperator("eq");
	        cons.add(con);	
       }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
	   List<Long> ids = _tbl_ThongTin_HocVienDao.findColumnByCondition(Tbl_ThongTin_HocVien.class,cons,columns, 1, 1);
	   return ids;
   }
   
   private List<Long> findMonHocId(String ma){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("ma");
	        con.setValue1(ma);
	        con.setOperator("eq");
	        cons.add(con);	
       }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
	   List<Long> ids = _tbl_CTDT_MonHocDao.findColumnByCondition(Tbl_CTDT_MonHoc.class,cons,columns, 1, 1);
	   return ids;
   }
   
   private List<Long> findNhomLopMonHocId(String ma, Long monhocId){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("ma");
	        con.setValue1(ma);
	        con.setOperator("eq");
	        cons.add(con);	
       }
       
       {
      	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("monHocId.id");
	        con.setValue1(monhocId);
	        con.setOperator("eq");
	        cons.add(con);	
      }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
	   List<Long> ids = _tbl_ThongTin_NhomLop_MonHocDao.findColumnByCondition(Tbl_ThongTin_NhomLop_MonHoc.class,cons,columns, 1, 1);
	   return ids;
   }
   
   private List<Tbl_DKMH_Ketqua> findKetQuaDKId(Long dotdkid, Long hocvienid, Long monhocid){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("dotDKId.id");
	        con.setValue1(dotdkid);
	        con.setOperator("eq");
	        cons.add(con);	
       }
       {
      	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("hocVienId.id");
	        con.setValue1(hocvienid);
	        con.setOperator("eq");
	        cons.add(con);	
      }
       
       {
     	 	ConditionReport con = new ConditionReport(); 
	       	con.setCol("NLMHId.monHocId.id");
	        con.setValue1(monhocid);
	        con.setOperator("eq");
	        cons.add(con);	
     }
	   List<Tbl_DKMH_Ketqua> ids = _tbl_DKMH_KetquaDao.findByCondition(Tbl_DKMH_Ketqua.class,cons, 1, 1);
	   return ids;
   }
	public final Boolean CalSPCopyKetquaDotDkHieuChinh(int dotDKHieuChinhId, int dotDKDuocHieuChinhId  ){
		return _tbl_DKMH_KetquaDao.CalSPCopyKetquaDotDkHieuChinh(dotDKHieuChinhId, dotDKDuocHieuChinhId);
		
	}

}//endclass

